package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.domain.CarPackageAudit;
import cn.wolfcode.car.business.domain.ServiceItem;
import cn.wolfcode.car.business.domain.Statement;
import cn.wolfcode.car.business.mapper.BpmnInfoMapper;
import cn.wolfcode.car.business.mapper.CarPackageAuditMapper;
import cn.wolfcode.car.business.mapper.ServiceItemMapper;
import cn.wolfcode.car.business.mapper.StatementMapper;
import cn.wolfcode.car.business.query.CarPackageAuditQueryObject;
import cn.wolfcode.car.business.service.ICarPackageAuditService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;

@Service
@Transactional
public class CarPackageAuditServiceImpl implements ICarPackageAuditService {

    @Autowired
    private CarPackageAuditMapper carPackageAuditMapper;
    @Autowired
    private StatementMapper statementMapper;
    @Autowired
    private BpmnInfoMapper bpmnInfoMapper;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private TaskService taskService;

    @Autowired
    private ServiceItemMapper serviceItemMapper;
    @Override
    public TablePageInfo<CarPackageAudit> query(CarPackageAuditQueryObject qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<CarPackageAudit>(carPackageAuditMapper.selectForList(qo));
    }


    @Override
    public void save(CarPackageAudit carPackageAudit) {
        carPackageAudit.setCreateTime(new Date());
        carPackageAuditMapper.insert(carPackageAudit);

    }

    @Override
    public CarPackageAudit get(Long id) {
        return carPackageAuditMapper.selectByPrimaryKey(id);
    }


    @Override
    public void update(CarPackageAudit carPackageAudit) {
        carPackageAuditMapper.updateByPrimaryKey(carPackageAudit);


    }

    @Override
    public void deleteBatch(String ids) {
        Long[] dictIds = Convert.toLongArray(ids);
        for (Long dictId : dictIds) {
            carPackageAuditMapper.deleteByPrimaryKey(dictId);
        }
    }

    @Override
    public List<CarPackageAudit> list() {
        return carPackageAuditMapper.selectAll();
    }

    @Override
    public InputStream processImg(Long id) throws IOException {
        //根据id拿到Car....表中的数据
        CarPackageAudit carPackageAudit = carPackageAuditMapper.selectByPrimaryKey(id);
        //拿bpmnId去拿到bpmn表中的数据
        BpmnInfo bpmnInfo = bpmnInfoMapper.selectByPrimaryKey(carPackageAudit.getBpmnInfoId());
        List<String> activeActivityIds = new ArrayList<>();
        //判读审核状态是否是进行中
        if(CarPackageAudit.STATUS_IN_ROGRESS.equals(carPackageAudit.getStatus())) {
            //在进行中
            //使用RunTimeService调用a方法拿到实例id
            activeActivityIds = runtimeService.getActiveActivityIds(carPackageAudit.getInstanceId());
        }else {
            //不是就设值为空集合
            activeActivityIds  = Collections.EMPTY_LIST;
        }
        //使用ddg设置高光,并使用部署id来获取bpmnModel
        InputStream inputStream = new DefaultProcessDiagramGenerator().generateDiagram(repositoryService.getBpmnModel(bpmnInfo.getActProcessId())
                , activeActivityIds, Collections.EMPTY_LIST
                , "宋体"
                , "宋体"
                , "宋体");
        return inputStream;
    }

    @Override
    public void cancelApply(Long id) {
        CarPackageAudit carPackageAudit = carPackageAuditMapper.selectByPrimaryKey(id);
        //判断是否是进行中
        if (!CarPackageAudit.STATUS_IN_ROGRESS.equals(carPackageAudit.getStatus())) {
            throw new BusinessException("非法操作");
        }
        //把car改为撤销状态
        carPackageAuditMapper.updateSataus(carPackageAudit.getId(),CarPackageAudit.STATUS_CANCEL);
        //把服务单项改为初始化
        serviceItemMapper.updateByStutas(carPackageAudit.getServiceItemId(), ServiceItem.AUDITSTATUS_INIT);
        //删除实例
        runtimeService.deleteProcessInstance(carPackageAudit.getInstanceId(), "删除");
    }

    @Override
    @Transactional
    public void audit(Long id, Long auditStatus, String info) {
        //判断是否是审核中
        CarPackageAudit carPackageAudit = carPackageAuditMapper.selectByPrimaryKey(id);
        if (!CarPackageAudit.STATUS_IN_ROGRESS.equals(carPackageAudit.getStatus())) {
            throw new BusinessException("非法操作");
        }
        //根据实例id查任务表
        Task task = taskService.createTaskQuery().processInstanceId(carPackageAudit.getInstanceId()).singleResult();

        //添加流程变量
        Map<String,Object> map = new HashMap<>();
        map.put("auditStatus",auditStatus);
        //处理任务并把流程变量加载进去
        taskService.complete(task.getId(), map);
        //判断是否通过
        if (CarPackageAudit.STATUS_PASS.equals(Integer.valueOf(auditStatus + ""))) {
            Task task2 = taskService.createTaskQuery().processInstanceId(carPackageAudit.getInstanceId()).singleResult();
            if (task2 != null) {
             //修改审核人
             carPackageAudit.setAuditorId(Long.valueOf(task2.getAssignee()));
            }else {
                carPackageAudit.setStatus(CarPackageAudit.STATUS_PASS);
                //修改car中状态改为审核拒绝状态
                carPackageAudit.setInfo(carPackageAudit.getInfo() + "<br>" + ShiroUtils.getUser().getUserName() + "【同意】,批注意见:"+info);
                //修改单项中的状态
                serviceItemMapper.updateByStutas(carPackageAudit.getServiceItemId(), ServiceItem.AUDITSTATUS_INIT);
            }
        }else {
            carPackageAudit.setStatus(CarPackageAudit.STATUS_REJECT);
            //修改car中状态改为审核拒绝状态
            carPackageAudit.setInfo(carPackageAudit.getInfo() + "<br>" + ShiroUtils.getUser().getUserName() + "【拒绝】,批注意见:"+info);
            //修改单项中的状态
            serviceItemMapper.updateByStutas(carPackageAudit.getServiceItemId(), ServiceItem.AUDITSTATUS_REPLY);
            //修改car表中的备注
            //添加审核时间

        }
        carPackageAudit.setAuditTime(new Date());
        carPackageAuditMapper.updateByPrimaryKey(carPackageAudit);
    }
}
